﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using RBAC.MaHaiBo.Entity;
using RBAC.MaHaiBo.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace RBAC.MaHaiBo.Service
{
    public class UserService : IUserService
    {
        /// <summary>
        /// 日志
        /// </summary>
        ILogger<UserService> logger;
        /// <summary>
        /// 用户仓储
        /// </summary>
        IUserRepository uRep;
        /// <summary>
        /// 省仓储
        /// </summary>
        IProvinceRepository pRep;
        /// <summary>
        /// 市仓储
        /// </summary>
        ICityRepository cityRep;
        /// <summary>
        /// 县仓储
        /// </summary>
        ICountyRepository couRep;
        /// <summary>
        /// 用户与角色关联仓储
        /// </summary>
        IUserRoleRepository urRep;
        /// <summary>
        /// 角色仓储
        /// </summary>
        IRoleRepository rRep;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="uRep">用户仓储</param>
        /// <param name="pRep">省仓储</param>
        /// <param name="cityRep">市仓储</param>
        /// <param name="couRep">县仓储</param>
        /// <param name="urRep">用户与角色关联仓储</param>
        /// <param name="rRep">角色仓储</param>
        public UserService(ILogger<UserService> logger,
        IUserRepository uRep,
         IProvinceRepository pRep,
         ICityRepository cityRep,
         ICountyRepository couRep,
          IUserRoleRepository urRep,
          IRoleRepository rRep
         )
        {
            this.logger = logger;
            this.uRep = uRep;
            this.pRep = pRep;
            this.cityRep = cityRep;
            this.couRep = couRep;
            this.urRep = urRep;
            this.rRep = rRep;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="user">要添加的用户信息</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> AddUser(UserInfo user)
        {
            try
            {
                var weiyi = await uRep.GetAsync(p => p.uName == user.uName && !p.deleteFlag);
                if (weiyi.Count > 0)
                {
                    return -1;
                }
                return await uRep.AddAsync(user);
            }
            catch (Exception ex)
            {
                logger.LogError("【用户服务层】 添加用户信息" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 批量修改用户信息
        /// </summary>
        /// <param name="Ids">要修改的用户编号集合</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> ByUpdateUser(List<int> Ids)
        {
            try
            {

                var list = uRep.GetAsync(p => Ids.Contains(p.uId));
                foreach (var item in await list)
                {
                    item.deleteFlag = true;
                }
                return await uRep.ByUpdateAsync(await list);


            }
            catch (Exception ex)
            {
                logger.LogError("【用户服务层】 批量修改用户信息" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 逻辑删除用户编号
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> DeleteUser(int uid)
        {
            try
            {
                var qauoy = await uRep.GetModelAsync(uid);
                qauoy.deleteFlag = true;
                return await uRep.UpdateAsync(qauoy);
            }
            catch (Exception ex)
            {
                logger.LogError("【用户服务层】 批量修改用户信息" + ex.Message);
                throw;
            }

        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="accountNumber">账号</param>
        /// <param name="password">密码</param>
        /// <returns>返回想要的数据信息</returns>
        public async Task<UserInfo> GeLohin(string accountNumber, string password)
        {
            try
            {
                var list = await uRep.GetAllAsync();
                var qount = list.FirstOrDefault(p => p.accountNumber == accountNumber&&p.password== password);
                return qount;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户服务层】 用户登录" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 显示全部用户信息
        /// </summary>
        /// <returns>返回用户数据集合</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<FenYeDTO<UserInfoDTO>> GetUser(int poageiden, int pageSzen ,string? Name )
        {
            try
            {
                var fy=new FenYeDTO<UserInfoDTO>();
                var urlist = await urRep.GetAllAsync();
                var rlist = await rRep.GetAllAsync();

                var list = (from user in await uRep.GetAllAsync()
                            join prog in await pRep.GetAllAsync()
                            on user.provinceId equals prog.provinceId
                            join city in await cityRep.GetAllAsync()
                           on user.cityId equals city.cityId
                            join county in await couRep.GetAllAsync()
                            on user.countyId equals county.countyId
                            where user.deleteFlag == false
                            select new UserInfoDTO
                            {
                                uId = user.uId,
                                uName = user.uName,
                                uSex = user.uSex,
                                provinceId = user.provinceId,
                                provinceName = prog.provinceName,
                                cityId = user.cityId,
                                cityName = city.cityName,
                                countyId = user.countyId,
                                countyName = county.countyName,
                                address = user.address,
                                creator = user.creator,
                                creationTime = user.creationTime,
                                modifier = user.modifier,
                                modificationTime = user.modificationTime,
                                deleteFlag = user.deleteFlag,
                                RName = (from ur in urlist
                                         join role in rlist
                                         on ur.Rid equals role.Rid
                                         where ur.Uid == user.uId
                                         select role).ToList()
                            });
                if (!string.IsNullOrWhiteSpace(Name) )
                {
                    list = list.Where(p => p.uName.Contains(Name));
                }
                fy.totyCount = list.Count();
                fy.pageCount = (int)Math.Ceiling(fy.totyCount * 1.0 / pageSzen);
                fy.list = list.OrderBy(p => p.uId).Skip((poageiden - 1) * pageSzen).Take(pageSzen).ToList();
                return fy;
            }
            catch (Exception ex)
            {
                logger.LogError("【用户服务层】 显示全部用户信息" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 反填用户数据信息
        /// </summary>
        /// <param name="uid">用户编号</param>
        /// <returns>返回数据信息</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<UserInfo> GetUserInfo(int uid)
        {
            try
            {
                return uRep.GetModelAsync(uid);

            }
            catch (Exception ex)
            {
                logger.LogError("【用户服务层】 反填用户数据信息" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user">修改后的数据信息</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdateUser(UserInfo user)
        {
            try
            {

                var weiyi = await uRep.GetAsync(p => p.uId != user.uId && !p.deleteFlag && p.uName == user.uName);
                if (weiyi.Count > 0)
                {
                    return -1;
                }
                user.modifier = "李四";
                user.modificationTime = DateTime.Now;
                return await uRep.UpdateAsync(user);

            }
            catch (Exception ex)
            {
                logger.LogError("【用户服务层】 批量修改用户信息" + ex.Message);
                throw;
            }
        }

    }
}
